package com.Jano.fillter;
import com.Jano.exception.BusinessException;
import com.Jano.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 这个过滤器通过ThreadLocal保存了本次请求过程中对应的请求和响应对象
 * 目的是为了在项目中任何地方都能获取本次请求和响应对象
 * 这样在很多方法中的参数中就可以省去请求对象或者响应对象了。
 * 对于Web项目而言，每个客户端请求对应的就是一个线程对象
 * 对于ThreadLocal如果第一阶段没有学习，可以参考给出的Demo
 *
 * 如果没有学习过ThreadLocal，这个Demo一定要好好看，并理解，不然这个过滤器同样看不明白
 */
public class ServletHolderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        RequestContextHolder.setRequest(req);
        RequestContextHolder.setResponse(res);
        filterChain.doFilter(req, res);
        RequestContextHolder.removeRequest();
        RequestContextHolder.removeResponse();
    }
    @Override
    public void destroy() {

    }
}
